<template>
  <!-- 需量下发 -->
  <div class="demand">
    <a-divider orientation="left" :dashed="true" style="font-size: 20px"
      >通用配置信息</a-divider
    >
    <a-descriptions
      title=""
      bordered
      :size="'small'"
      :column="6"
      :labelStyle="{ width: '160px' }"
      :content-style="{ width: '120px' }"
    >
      <template v-if="showModeOrNo">
        <a-descriptions-item label="指令模式" :span="2">
          <template v-if="!isPowercmdEdit">
            {{ powercmdType || "暂无" }}
          </template>
          <template v-else>
            <a-select
              ref="select"
              v-model:value="chosePowercmdType"
              class="formSelect"
              placeholder="请选择"
              style="width: 100%"
            >
              <a-select-option
                v-for="item in POWERCMD_TYPELIST"
                :key="item.typeid"
                :value="item.typeid"
                :disabled="item.typeid !== 3"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </template>
        </a-descriptions-item>
        <a-descriptions-item label="操作" :span="2">
          <template v-if="!isPowercmdEdit">
            <a-button
              type="primary"
              class="bluePlainBtn"
              @click="powercmdEdit"
              :size="'small'"
            >
              编辑
            </a-button>
          </template>
          <template v-else>
            <a-space>
              <a-button
                type="primary"
                :loading="isPowerLoading"
                :size="'small'"
                @click="handlePowerSave"
                >保存</a-button
              >
              <a-button :size="'small'" @click="handlePowercmdCancel"
                >取消</a-button
              >
            </a-space>
          </template>
        </a-descriptions-item>
        <a-descriptions-item label="" :span="2"> </a-descriptions-item>
      </template>
      <a-descriptions-item label="是否存在计量点" :span="2">
        <template v-if="!pointEdit">
          {{ { 0: "否", 1: "是" }[pointObj.point] || "--" }}
        </template>
        <template v-else>
          <a-select
            ref="select"
            v-model:value="pointForm.point"
            class="formSelect"
            placeholder="请选择"
            @change="changeMulti"
            style="width: 100%"
          >
            <a-select-option :value="0">否</a-select-option>
            <a-select-option :value="1">是</a-select-option>
          </a-select>
        </template>
      </a-descriptions-item>
      <a-descriptions-item label="计量点统计范围" :span="2">
        <template v-if="!pointEdit">
          {{ pointObj.statisticsName || "--" }}
        </template>
        <template v-else>
          <a-select
            ref="select"
            mode="multiple"
            show-search
            v-model:value="pointForm.linkDeviceIds"
            class="formSelect"
            placeholder="请选择"
            :disabled="pointForm.point === 0"
            allow-clear
            style="width: 100%"
          >
            <a-select-option
              v-for="item in linkList"
              :key="item.deviceId"
              :value="item.deviceId"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </template>
      </a-descriptions-item>
      <a-descriptions-item label="操作" :span="2">
        <template v-if="!pointEdit">
          <a-button
            type="primary"
            class="bluePlainBtn"
            @click="pointObjEdit"
            :size="'small'"
          >
            编辑
          </a-button>
        </template>
        <template v-else>
          <a-space>
            <a-button
              type="primary"
              :loading="loading"
              :size="'small'"
              @click="handlePointSave"
              >保存</a-button
            >
            <a-button :size="'small'" @click="handlePointCancel">取消</a-button>
          </a-space>
        </template>
      </a-descriptions-item>
    </a-descriptions>
    <a-divider
      orientation="left"
      :dashed="true"
      style="font-size: 20px; margin-top: 60px"
      >需量/防逆流信息</a-divider
    >
    <a-descriptions
      title=""
      bordered
      :size="'small'"
      :column="8"
      :labelStyle="{ width: '160px' }"
      :content-style="{ width: '120px' }"
      style="margin-top: 40px"
    >
      <template v-for="(group, groupIndex) in demandData" :key="groupIndex">
        <template v-for="(item, index) in group.lineItems" :key="index">
          <a-descriptions-item :span="2">
            <template #label>
              <div v-if="item.notFrequent">
                {{ item.showName }}<br />(请勿频繁操作)
              </div>
              <div v-else>{{ item.showName }}</div>
            </template>
            <template v-if="!isEditing[groupIndex]">
              <div>
                <template
                  v-if="item.webShowType !== 2 && item.hasOwnProperty('value')"
                  >{{ item.value }} {{ item.unit }}</template
                ><template
                  v-else-if="
                    item.webShowType === 2 && item.hasOwnProperty('value')
                  "
                  >{{ item.value ? "开" : "关" }}</template
                ><template v-else>--</template>
              </div>
            </template>
            <template v-else>
              <a-switch
                v-model:checked="item.value"
                v-if="item.webShowType === 2"
              />
              <!-- <a-select
                v-model:checked="item.value"
                v-else-if="item.webShowType === 3"
              ></a-select> -->
              <a-input-number
                v-model:value="item.value"
                style="width: 100%"
                :size="'small'"
                :controls="false"
                v-else
              />
            </template>
          </a-descriptions-item>
        </template>
        <!-- 操作列 -->
        <a-descriptions-item label="操作" :span="2">
          <template v-if="!isEditing[groupIndex]">
            <a-button
              type="primary"
              class="bluePlainBtn"
              @click="startEdit(groupIndex, 1)"
              :size="'small'"
            >
              编辑
            </a-button>
          </template>
          <template v-else>
            <a-space>
              <a-button
                type="primary"
                :size="'small'"
                :loading="isLoading[groupIndex]"
                @click="handleSave(groupIndex, 1)"
                >保存</a-button
              >
              <a-button :size="'small'" @click="handleCancel(groupIndex, 1)"
                >取消</a-button
              >
            </a-space>
          </template>
        </a-descriptions-item>
        <!-- 填充空白单元格 -->
        <template v-if="group.lineItems.length < 3">
          <a-descriptions-item
            v-for="i in 3 - group.lineItems.length"
            :key="'empty-' + i"
            :span="2"
            label=""
          >
          </a-descriptions-item>
        </template>
      </template>
    </a-descriptions>
    <template v-if="airCondition.length > 0">
      <a-divider
        orientation="left"
        :dashed="true"
        style="font-size: 20px; margin-top: 60px"
        >空调策略控制</a-divider
      >
      <a-descriptions
        title=""
        bordered
        :size="'small'"
        :column="8"
        :labelStyle="{ width: '160px' }"
        :content-style="{ width: '120px' }"
        style="margin-top: 40px"
      >
        <template v-for="(group, groupIndex) in airCondition" :key="groupIndex">
          <template v-for="(item, index) in group.lineItems" :key="index">
            <a-descriptions-item :span="2">
              <template #label>
                <div v-if="item.notFrequent">
                  {{ item.showName }}<br />(请勿频繁操作)
                </div>
                <div v-else>{{ item.showName }}</div>
              </template>
              <template v-if="!isEditing[groupIndex]">
                <div>
                  <template
                    v-if="
                      item.webShowType !== 2 && item.hasOwnProperty('value')
                    "
                    >{{ item.value }} {{ item.unit }}</template
                  ><template
                    v-else-if="
                      item.webShowType === 2 && item.hasOwnProperty('value')
                    "
                    >{{ item.value ? "开" : "关" }}</template
                  ><template v-else>--</template>
                </div>
              </template>
              <template v-else>
                <a-switch
                  v-model:checked="item.value"
                  v-if="item.webShowType === 2"
                />
                <!-- <a-select
                v-model:checked="item.value"
                v-else-if="item.webShowType === 3"
              ></a-select> -->
                <a-input-number
                  v-model:value="item.value"
                  style="width: 100%"
                  :size="'small'"
                  :controls="false"
                  v-else
                />
              </template>
            </a-descriptions-item>
          </template>
          <!-- 操作列 -->
          <a-descriptions-item label="操作" :span="2">
            <template v-if="!isEditing[groupIndex]">
              <a-button
                type="primary"
                class="bluePlainBtn"
                @click="startEdit(groupIndex, 2)"
                :size="'small'"
              >
                编辑
              </a-button>
            </template>
            <template v-else>
              <a-space>
                <a-button
                  type="primary"
                  :size="'small'"
                  :loading="isLoading[groupIndex]"
                  @click="handleSave(groupIndex, 2)"
                  >保存</a-button
                >
                <a-button :size="'small'" @click="handleCancel(groupIndex, 2)"
                  >取消</a-button
                >
              </a-space>
            </template>
          </a-descriptions-item>
          <!-- 填充空白单元格 -->
          <template v-if="group.lineItems.length < 3">
            <a-descriptions-item
              v-for="i in 3 - group.lineItems.length"
              :key="'empty-' + i"
              :span="2"
              label=""
            >
            </a-descriptions-item>
          </template>
        </template>
      </a-descriptions>
    </template>
  </div>
</template>

<script setup>

import { POWERCMD_TYPELIST, POWERCMD_TYPEOBJ } from "@/constants/powercmdType"
// 
const $api = inject("$api")
const props = defineProps({
  linkDeviceId: {
    type: Number,
    default: null,
  },
  energyLinkList: {
    type: Array,
    default: [],
  },
})
const emit = defineEmits(["loading-change"])
const loading = ref(false)
const setLoading = (status) => {
  loading.value = status
  emit("loading-change", status)
}
//查询电池堆计量点信息
const pointObj = ref({})
const pointEdit = ref(false)
const getPointFind = async (id) => {
  setLoading(true)
  try {
    const res = await $api.pointFind({ linkDeviceId: id })
    if (res && res.code === 0) {
      pointObj.value = res.data
      if ("point" in pointObj.value) {
        if (pointObj.value.point === 1) {
          const mainName = pointObj.value.name.replace(/#/g, "")
          const childNames = pointObj.value.pointChildList.map((item) =>
            item.name.replace(/#/g, "")
          )
          pointObj.value.statisticsName = childNames.join("、")
        } else {
          pointObj.value.statisticsName = ""
        }
      }
    }
  } catch (error) {
    console.error(error)
  } finally {
    setLoading(false)
  }
}
//计量点编辑设置
const pointForm = ref({
  linkDeviceId: null,
  point: null,
  linkDeviceIds: [],
})
const copyPointObj = ref({})
const pointObjEdit = () => {
  pointForm.value.point = pointObj.value.point
  if (pointObj.value.point === 1) {
    pointForm.value.linkDeviceIds = pointObj.value.pointChildList.map(
      (item) => item.deviceId
    )
  } else {
    pointForm.value.linkDeviceIds = []
  }

  copyPointObj.value = JSON.parse(JSON.stringify(pointObj.value))
  pointEdit.value = true
}
//保存计量点设置
const handlePointSave = async () => {
  loading.value = true
  try {
    const res = await $api.pointSet(pointForm.value)
    if (res && res.code === 0) {
      message.success("保存成功")
      pointEdit.value = false
      getPointFind(form.value.linkDeviceId) // 重新获取数据
      getCcuItem(form.value.linkDeviceId)
    }
  } catch (error) {
    message.error("保存失败")
  }
  loading.value = false
}
//取消计量点设置
const handlePointCancel = () => {
  pointObj.value = JSON.parse(JSON.stringify(copyPointObj.value))
  pointEdit.value = false
}
//是否计量点选择改变，联动统计范围选择
const changeMulti = (e) => {
  if (e === 0) {
    pointForm.value.linkDeviceIds = []
  }
}
const demandData = ref([])
const form = ref({
  linkDeviceId: null,
  items: [],
})
//获取设置项
const airCondition = ref([])
const getCcuItem = async (id) => {
  setLoading(true)
  try {
    const res = await $api.ccuItem({ linkDeviceId: id })
    if (res && res.code === 0) {
      // 处理demandData中的lineItems数据
      res.data.forEach((group) => {
        group.lineItems.forEach((item) => {
          if (item.webShowType === 2) {
            // 将value值转换为布尔值
            if (item.hasOwnProperty("value")) {
              item.value = item.value === "1" || item.value === 1
            }
          }
        })
      })
      demandData.value = res.data.filter((item) => item.ctrlPanelType === 1)
      airCondition.value = res.data.filter((item) => item.ctrlPanelType === 2)
    }
  } catch (error) {
    console.error(error)
  } finally {
    setLoading(false)
  }
}
// 每行的编辑状态和loading
const isEditing = ref({})
const isLoading = ref({})
// 缓存编辑前的数据
const originalData = ref({})

const startEdit = (groupIndex, type) => {
  // 判断是需量还是空调策略
  let currentData =
    type === 1 ? demandData.value[groupIndex] : airCondition.value[groupIndex]
  if (currentData.hasOwnProperty("forbidEdit") && currentData.forbidEdit) {
    Modal.error({
      title: "温馨提示",
      content: currentData.forbidEditTip || "该组数据禁止编辑",
    })
  } else if (currentData.hasOwnProperty("clickIGotItTip")) {
    Modal.warning({
      title: "温馨提示",
      content: currentData.clickIGotItTip || "请谨慎编辑数据",
      onOk() {
        handleEditData(groupIndex, type)
      },
    })
  } else {
    handleEditData(groupIndex, type)
  }
}
const handleEditData = (groupIndex, type) => {
  let data =
    type === 1 ? demandData.value[groupIndex] : airCondition.value[groupIndex]
  data.lineItems.forEach((item) => {
    if (item.webShowType === 2) {
      // 如果没有value属性，设置默认值为0
      if (!("value" in item)) {
        item.value = 0
      }
      // 如果value值为undefined或null，设置默认值为0
      if (item.value === undefined || item.value === null) {
        item.value = 0
      }
    }
  })
  originalData.value[groupIndex] = JSON.parse(JSON.stringify(data))
  isEditing.value[groupIndex] = true
}

const handleSave = async (groupIndex, type) => {
  const data =
    type === 1 ? demandData.value[groupIndex] : airCondition.value[groupIndex]
  isLoading.value[groupIndex] = true
  try {
    const currentGroup = data
    // 在保存前将布尔值转换回0/1
    currentGroup.lineItems.forEach((item) => {
      if (item.webShowType === 2) {
        item.value = item.value ? 1 : 0
      }
    })
    // 检查所有项的requestUrl是否相同
    const firstUrl = currentGroup.lineItems[0]?.requestUrl
    const allSameUrl = currentGroup.lineItems.every(
      (item) => item.requestUrl === firstUrl
    )

    if (allSameUrl && firstUrl) {
      // 如果所有URL相同，合并为一个请求
      const items = currentGroup.lineItems.map((item) => ({
        requestNameAndEvent: item.requestNameAndEvent,
        value:
          item.webShowType === 2 ? item.value : item.value ? item.value : "",
      }))
      const params = {
        linkDeviceId: form.value.linkDeviceId,
        items,
      }
      const res = await $api.setItem(params, firstUrl)
      if (res && res.code === 0) {
        message.success("保存成功")
      }
    } else {
      // 如果URL不同，分别发送请求
      const promises = currentGroup.lineItems.map((item) => {
        const params = {
          linkDeviceId: form.value.linkDeviceId,
          items: [
            {
              requestNameAndEvent: item.requestNameAndEvent,
              value:
                item.webShowType === 2
                  ? item.value
                  : item.value
                  ? item.value
                  : "",
            },
          ],
        }
        return $api.setItem(params, item.requestUrl)
      })

      const results = await Promise.all(promises)
      const allSuccess = results.every((res) => res && res.code === 0)
      if (allSuccess) {
        message.success("保存成功")
      }
    }
    getCcuItem(form.value.linkDeviceId) // 重新获取数据
    isEditing.value[groupIndex] = false
  } catch (error) {
    message.error("保存失败")
  }
  isLoading.value[groupIndex] = false
}

const handleCancel = (groupIndex, type) => {
  let data =
    type === 1 ? demandData.value[groupIndex] : airCondition.value[groupIndex]
  data = JSON.parse(JSON.stringify(originalData.value[groupIndex]))
  isEditing.value[groupIndex] = false
}
//是否展示指令模式
const showModeOrNo = ref(false)

const showMode = async (id) => {
  const res = await $api.showMode({
    linkDeviceId: id,
  })
  if (res && res.data) {
    showModeOrNo.value = res.data
    if (showModeOrNo.value) {
      getPowercmdType(id)
    }
  }
}
//获取当前指令模式
const chosePowercmdType = ref(null)
const powercmdType = ref()
const getPowercmdType = async (id) => {
  const res = await $api.getPowercmd({
    linkId: id,
  })
  if (res && res.data) {
    showModeOrNo.value = res.data
    powercmdType.value = res.data ? POWERCMD_TYPEOBJ[res.data[0]] : "暂无"
    chosePowercmdType.value = res.data[0]
  }
}
//编辑指令模式
const isPowercmdEdit = ref(false)
const copyMode = ref(null)
const powercmdEdit = () => {
  isPowercmdEdit.value = true
  copyMode.value = chosePowercmdType.value
}
//下发指令
const isPowerLoading = ref(false)
const handlePowerSave = async () => {
  isPowerLoading.value = true
  try {
    const res = await $api.pubPowercmd({
      mode: chosePowercmdType.value,
      linkId: form.value.linkDeviceId,
    })
    if (res && res.code === 0) {
      message.success("保存成功")
      getPowercmdType(form.value.linkDeviceId)
    }
  } catch (error) {
    console.error(error)
  }
  isPowercmdEdit.value = false
  isPowerLoading.value = false
}
//取消编辑
const handlePowercmdCancel = () => {
  isPowercmdEdit.value = false
}
watch(
  () => props.linkDeviceId,
  async (val) => {
    if (val) {
      form.value.linkDeviceId = val
      pointForm.value.linkDeviceId = val
      await showMode(form.value.linkDeviceId)

      /* getPointFind()
      getCcuItem() */
    }
  }
)
const linkList = ref([])
watch(
  () => props.energyLinkList,
  async (val) => {
    if (val) {
      linkList.value = val
    }
  }
)
onMounted(async () => {})
defineExpose({ getPointFind, getCcuItem })
</script>

<style lang="less" scoped>
.demand {
  margin-top: 60px;
  .title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 16px;
  }

  .info-content,
  .config-content {
    padding: 20px;
    border-radius: 4px;
  }

  .info-row,
  .config-row {
    margin-bottom: 16px;
    display: flex;
    align-items: center;

    .label {
      width: 140px;
      text-align: right;
      margin-right: 8px;
    }

    .value {
      flex: 1;
      span {
        cursor: pointer;
        &:hover {
          color: #1890ff;
        }
      }
      .ant-btn {
        margin-left: 8px;
      }
    }
  }

  .battery-config {
    margin-top: 24px;
  }
}
</style>
